<Advent of Code 2025 day 4> (spoilers) :thread:
# advent-of-code
a
m
Part 1
Part 2
As usual, grids make an appearance! Having helpers methods like
toGrid()
and
getAdjacent()
at the ready helped a lot.
d
Need to clean mine up but that was also fun and quick: https://github.com/dfings/advent-of-code/blob/main/src/2025/problem_4.main.kts
m
This the type of day where having just a couple of helper functions readily available speeds up your logic a ton.
toGrid()
makes a Map<PairInt, Int, Char> of the input solution.
winds()
returns its 8 neighbour points
👍 1
n
Yeah, my
CharArea
is similar to your
Grid
.
Copy code
fun one(input: List<String>): Int {
        val area = parse(input)
        return area.tiles { it == '@' }.count { area.neighbors8(it, '@').size < 4 }
    }
d
Good enough for now
m
There are 2 types of people.
List<List<T>>
and
Map<Point, T>
. 😄
👆 2
d
A lot of times I do
Map<Point, T>
but part 1 was so easy with
List<String>
alone and I just extended the count function to remove optionally
j
Yeah I'm a
set<Pos>
type:
Copy code
fun List<CharSequence>.findAll(ch: Char): Set<Pos> = flatMapIndexed { r, line ->
    line.mapIndexedNotNull { c, ch1 -> if (ch1 == ch) Pos(r, c) else null }
}.toSet()

fun part1(data: String): Any {
    val rolls = data.lines().findAll('@')
    return rolls.count(rolls::accessible)
}

fun part2(data: String): Any {
    val rolls = data.lines().findAll('@').toMutableSet()
    var result = 0
    while (true) {
        val removed = rolls.filter(rolls::accessible).toSet()
        result += removed.size
        rolls -= removed
        if (removed.isEmpty()) break
    }
    return result
}

private fun Set<Pos>.accessible(pos: Pos): Boolean =
    listOf(pos.n(), pos.e(), pos.s(), pos.w(), pos.ne(), pos.se(), pos.sw(), pos.nw()).count(this::contains) < 4
m
That also works nicely for boolean grids!
y
Since I decided to start fresh new this year, it kind of took a bit of boilerplate to implement the needed logic 😢
➕ 1
b
I couldn't remember how to use my helper functions and didn't want to take the time to look them up so i just did it with
Map
, again with some recursion
j
That also works nicely for boolean grids!
Why only boolean? It actually works great for any kind of maps 🙂 And in bonus, I do not need to worry about going out of bounds.
(the only drawback is that during parsing, I need to go through each possible
char
separately)
b
i also use maps so i don't have to bounds check, but set works too. im guessing he means binary grids? something is either present or not
m
really wish generateSequence has some build-in 'generate until difference' function. Too many times I'm trying to make a functional version of
Copy code
var current = parsed
while(true){
    val step = current.step()
    when(step){
        current -> break
        else -> current = step
    }
}
and it ends up looking very clunky in my solution:
Copy code
val current = generateSequence(parsed, Grid<Char>::step)
    .zipWithNext()
    .takeWhile { it.first != it.second }
    .last().second
m
Short and sweet 🙂
Copy code
fun main() {
    val grid = generateSequence(::readLine).flatMapIndexed { y, line ->
        line.mapIndexedNotNull { x, char -> if (char == '@') x to y else null }
    }.toMutableSet()

    fun liftable() = grid.filter { (px, py) ->
        (-1..1).flatMap { y -> (-1..1).map { px + it to py + y } }.count { it in grid } <= 4
    }.toSet()

    var lifted = 0
    while (true) {
        val liftable = liftable()
        if (lifted == 0) println(liftable.size)

        if (liftable.isEmpty()) break
        grid -= liftable
        lifted += liftable.size
    }

    println(lifted)
}
a
There are 2 types of people.
List<List<T>>
and
Map<Point, T>
.
I have both in Utils (I think) but I primarily
Map<Point, T>
so it avoid most O(n) issues and free-null when a point isn't there.
m
^ The third type would be
List<String>
. That's my default, until something else is needed 🙂
😱 1
a
how do you do neighbour-checking? index math for same row but for columns/above? you'd also need to know the number of columns, right?
m
^ No, for this problem I quickly moved on to Map, but then reduced it to
SetPair
since that was all that was needed.
a
yup, same (almost)... hmm I should optimise a bit I left the original data immutable
MapPoint, T
and during neighbour checks, I have a
SetPoint
for removedPoints which I check during the neighbour check. reducing it just to a
SetPoint
would be much clener
b
ok I should have used my util function, it makes it much simpler
m
^ I'm kind of old school and solve AoC without any prepared code 🙂
y
Much easier after/if you remember what it does after a year 😅
➕ 2
m
it just helps me mentally to see a grid like pattern and always think about grid operations in a map<Point, T>, even if another data type might be 'faster'. Like Anirudh says; you get a free null point as well, whereas if you would have indexed lists you'd have to boundary check
y
^ I'm kind of old school and solve AoC without any prepared code 🙂
I am starting to think (after 5th aoc) that it's actually the right way. Because you learn how to write utility functions after many years much faster than it takes to understand them afterwards
a
I had a "mapper" function in there for some reason 😖 apparently I don't always keep my chars and want to map them to something else. took a whole 5 mins to realise the "default" would be just
mapper = { c: Char -> c }
m
^ No right or wrong here. Years ago I prepared an elaborate utility function for breadth-first search and ended up never using it ...
b
thats why i usually just use them to clean up the code afterwards
K 1
n
Copy code
private fun solve(loop: Boolean): Int {
    val grid = input.toMutableGrid { c -> c == '@' }
    var totalRemoved = 0
    var removed = 0
    do {
        val removable = grid.withIndex()
            .filter { (idx, b) ->
                if (b) {
                    grid.getNeighbors(idx, true).count { it } < 4
                } else {
                    false
                }
            }
        for ((idx, _) in removable) {
            grid[idx] = false
        }
        removed = removable.size
        totalRemoved += removed
    } while (loop && removed != 0)
    return totalRemoved
}
n
could use
Copy code
do {
    ...
    totalRemoved += removable.size
} while (loop && removable.isNotEmpty())
👍 1
n
definitely cleaner that way
BTW, one of the things I love about Kotlin is that they didn't skimp on having lots of variations of the same thing, so long as they had a good name for it. One of my pet peeves in Rust is having to do something like
while !foo.is_empty() ...
when it's so much clearer to be able to say
while (foo.isNotEmpty())
➕ 1
y
Nah guys, my software brain rejects to write code without domain definitions... https://github.com/y9san9/aoc25/blob/main/day4.part2.main.kts
a
@Neil Banman same. been learning JS/TS recently and I really dislike that tiny
!
at the beginning of a check. makes it hard to read whether it's being inverted or not. especially when using long expressions rather than just variables
n
@Michael de Kaste
really wish generateSequence has some build-in 'generate until difference' function.
Copy code
fun <T> Sequence<T>.stabilized() = zipWithNext().first { (prev, next) -> prev == next }.first

fun <T> Sequence<IndexedValue<T>>.stabilized() = zipWithNext()
    .first { (prev, next) -> prev.value == next.value }.first
a
using sets and putting the 'end of sequence' outside, reduced part 2 to:
Copy code
fun partTwo(): Int {
    val removeSeq = generateSequence(data.keys to 0) { (points, _) ->
        val remove = points.filter { pt ->
            pt.neighbours().count { it in points } < 4
        }
        points - remove.toSet() to remove.size
    }
    return removeSeq.drop(1).map { it.second }.takeWhile { it != 0 }.sum()
}
(PS. wish Slack would let us put the language after the three backticks. like StackOverflow ```kotlin )
y
About Sequences, why not: generateSequence { diff -> ... } .takeWhile { diff > 0 }
n
I'm kind of old school and solve AoC without any prepared code 🙂
I'm not at all, but I really enjoy treating a String as a grid when I don't need to mutate anything. It's actually really ergonomic to navigate a String in 2D. The
\n
s make it easy to do bounds checks and prevent rollovers from far right to far left.
👍 1
e
the ability to
return
from an expression function is new
or hmm, https://youtrack.jetbrains.com/issue/KT-76926 says it's in 2.3.0 but I'm using 2.2.21, so I'm not sure why it's allowed here
e
pretty happy with the compactness today:
Copy code
// from previous years, I have Coord implemented:
// data class Coord(val x: Int, val y: Int) : ComparableCoord
fun main() {
    solve("Printing Department") {
        val input = lines.toGrid { it } // MapCoord, Char
        
        fun Map.EntryCoord, Char.removable() =
            this.value == '@' && this.key.neighbours(true).count { c -> input[c] == '@'} < 4

        part1 { input.count { it.removable() } }

        part2 {
            var sum = 0
            while(true) {
                input
                    .filter { it.removable() }
                    .takeIf { it.isNotEmpty() }
                    ?.forEach { (c, _) -> input[c] = '.'; sum++ }
                    ?: break
            }
            sum
        }
    }
}
y
How is coord comparable? Is (1,2) greater or lesser than (2,1)? Or are they equal? But == is false in that case
m
With a good grid helper...
n
Can’t answer for Endre but my Coord is Comparable using manhattan distance. You point out an inconsistency with equality that could cause problems. I’ll probably just pick x arbitrarily as a tiebreaker.
m
pretty happy with the compactness today
You're using a lot of hidden code though 🙂
💯 2
y
@Neil Banman when I wrote such helpers I had Coord.manhattan and comparison was unambiguous in that case:
if (x.manhattan > y.manhattan)
p
I surprisingly didn't have Grid/Point helpers ready so just went simple for this morning.
m
Compact solution using sequence:
Copy code
fun main() = generateSequence(::readLine)
    .flatMapIndexed { y, line -> line.mapIndexedNotNull { x, char -> if (char == '@') x to y else null } }
    .toMutableSet().let { grid ->
        generateSequence {
            grid.filter { (px, py) ->
                (-1..1).flatMap { y -> (-1..1).map { px + it to py + y } }.count { it in grid } <= 4
            }.toSet().also { grid -= it }.size.takeIf { it > 0 }
        }.toList().let {
            println(it.first())
            println(it.sum())
        }
    }
a
> or hmm, https://youtrack.jetbrains.com/issue/KT-76926 says it's in 2.3.0 but I'm using 2.2.21, so I'm not sure why it's allowed here @ephemient apparently that was added in 2.2.20 Support for
return
statements in expression bodies with explicit return types: whatsnew2220 link it's in
2.2.20-dev-8187
(for 2.2.21). and also maybe you set
language-version
to 2.3?
e
I didn't set
-language-version
. maybe it's a compiler bug that allows it in 2.2, not complaining, just surprised
👍 1
treating part 2 like a flood fill makes it faster, and it's possible to do while still computing part 1 first
k
I implemented a highly optimized linear O(N) solution treating the grid as a graph, where the removal process mimics K-Core decomposition using a queue-based BFS. To maximize performance, I utilized a "handshake" optimization during the initialization phase: by iterating through the grid once and checking only 4 "forward" directions (instead of all 8), I simultaneously updated the counts for both the current cell and its neighbor, effectively halving the memory access overhead. This approach, combined with flattened array indexing for better cache locality, allowed me to solve both parts with a total execution time of just 8ms.
Copy code
import java.util.ArrayDeque
import kotlin.time.measureTimedValue

fun main() {
    fun partOneAndTwo(lines: ListString): PairInt, Int {
        data class Cell(var counts: Int, var isPaper: Boolean, var removed: Boolean)
        data class Offset(val row: Int, val col: Int)
        val (rows, cols) = lines.size to lines.first().length
        val totalCells = rows * cols
        val cells = List(totalCells) { Cell(counts = 0, isPaper = false, removed = false) }
        val n4 = listOf(Offset(0, 1), Offset(1, -1), Offset(1, 0), Offset(1, 1))
        val n8 = n4 + listOf(Offset(-1, -1), Offset(-1, 0), Offset(-1, 1), Offset(0, -1))
        val queue = ArrayDequeInt()
        for (i in cells.indices) {
            val (r, c) = i / cols to i % cols
            if (lines[r][c] == '@') {
                cells[i].isPaper = true
                n4.map { (dr, dc) -> Offset(dr + r, dc + c) }
                    .filter { (nr, nc) -> nr in 0..<rows && nc in 0..<cols && lines[nr][nc] == '@' }
                    .forEach { (nr, nc) -> cells[i].counts++; cells[nr * cols + nc].counts++ }
            }
        }
        var part1Count = 0
        cells.forEachIndexed { index, cell ->
            if (cell.isPaper && cell.counts < 4) {
                queue.add(index)
                cell.removed = true
                part1Count++
            }
        }
        var part2Removed = part1Count
        while (!queue.isEmpty()) {
            val currentIdx = queue.poll()
            val (r, c) = currentIdx / cols to currentIdx % cols
            n8.map { (dr, dc) -> Offset(dr + r, dc + c) }
                .filter { (nr, nc) -> nr in 0..<rows && nc in 0..<cols }
                .map { (nr, nc) -> nr * cols + nc }
                .filter { i -> cells[i].isPaper && !cells[i].removed }
                .forEach { i ->
                    cells[i].counts--
                    if (cells[i].counts < 4) {
                        cells[i].removed = true
                        queue.add(i)
                        part2Removed++
                    }
                }
        }
        return part1Count to part2Removed
    }
    val (p1Test, p2Test) = partOneAndTwo(readInput("Day04_test"))
    check(p1Test == 13) { "Part 1 Test: $p1Test (Expected: 13)" }
    check(p2Test == 43) { "Part 2 Test: $p2Test (Expected: 43)" }
    val input = readInput("Day04")
    val (result, time) = (1..10).map { measureTimedValue { partOneAndTwo(input) } }.minBy { it.duration }
    println("Part 1: ${result.first}")
    println("Part 2: ${result.second}")
    println("Time: $time")
}
https://github.com/karloti/aoc-2025-in-kotlin/blob/main/src/Day04.kt
think smart 1
j
smart but do you really need BFS here?
or is it to avoid grid modification after each turn?
k
To guarantee O(N) complexity, yes. A naive iterative approach (scanning the grid repeatedly until stability) works for simple cases but degrades to O(N²) in worst-case scenarios—like a long 'fuse' or spiral pattern where removals cascade sequentially. The queue ensures I only re-evaluate cells that actually had a neighbor removed, keeping it strictly linear.
👍 1
j
double-smart, I get it. Thanks for explanation
K 1
not sure though if it's still a "search" tho, after all it's just a queue
k
@Jakub Gwóźdź Fair point! You're right, it's technically state propagation (or peeling) rather than a search for a target. It's essentially Kahn’s algorithm or K-Core decomposition under the hood. I just used 'BFS' as a shorthand for the FIFO traversal pattern, but 'Queue-based propagation' is definitely the more precise term.
e
basically the same as what I meant by flood fill above
👍 1
j
Since it’s a grid, I felt another visualization was called for.
🙌 2
k
Day04.mp4
❤️ 3
Day04_test.mp4
🙌 1
p
https://github.com/PaulWoitaschek/AdventOfCode/commit/62f1c300e58cef39bab82962bf2aa6d1e5c7ac58 Fun one nevertheless 🙂. let’s see how difficulty evolves over the next 8 days
j
I re-did my solution but used stack instead of queue, so it looks more like in one-pass:
😍 1
very nice 1
e
@y9san9 I use lexicographical ordering:
Copy code
data class Coord(val x: Int, val y: Int) : ComparableCoord {
    override fun compareTo(other: Coord): Int = this.x.compareTo(other.x).takeIf { it != 0 } ?: this.y.compareTo(other.y)
}
e
alternatively,
Copy code
override fun compareTo(other, coord): Int = compareValuesBy(this, other, Coord::x, Coord::y)
👍 1
p
Trusty old BitSet for speed. <500us for part2 (which also calculates part1)
Copy code
finished warmup after 10.021194500s
year 2025 day 4 part 1
	 BitSet took 140.877us 👑: 1527
	 Default took 371.725us (2.64x): 1527
year 2025 day 4 part 2
	 BitSet took 498.471us 👑: 8690
	 Default took 10.900457ms (21.87x): 8690
🙌 1